/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
  if (!head) return null
  const nodeArr = []
  let headNode = head
  let node = null
  let index = 0
  let current = null
  while (headNode) {
    index++
    nodeArr.push(headNode)
    if (!(index % 2)) {
      let firstPop = nodeArr.pop()
      let secondPop = nodeArr.pop()
      headNode = firstPop.next
      firstPop.next = secondPop
      current = secondPop
      secondPop.next = null
      lastnode = node
      while (lastnode && lastnode.next) {
        lastnode = lastnode.next
      }
      lastnode ? (lastnode.next = firstPop) : (node = firstPop)
    } else {
      headNode = headNode.next
    }
  }
  if (nodeArr.length > 0) {
    if (current) {
      current.next = nodeArr[0]
    } else {
      node = nodeArr[0]
    }
  }
  return node
}
const createListNode = arr => {
  function ListNode(val, next) {
    this.val = val === undefined ? 0 : val
    this.next = next === undefined ? null : next
  }
  let oldListNode = null
  for (let index = arr.length - 1; index > -1; index--) {
    const val = arr[index]
    const newListNode = new ListNode(val, oldListNode)
    oldListNode = newListNode
  }
  return oldListNode
}
console.log(swapPairs(createListNode(['1'])))
